package com.adrainty.spring;

import com.adrainty.spring.annotation.Autowire;
import com.adrainty.spring.annotation.Component;
import com.adrainty.spring.annotation.ComponentScan;
import com.adrainty.spring.annotation.Scope;
import com.adrainty.spring.utils.FileUtil;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ApplicationContext {

    private final Class<?> configClass;

    private final ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    public ApplicationContext(Class<?> configClass)  {
        this.configClass = configClass;

        // 获取扫描路径
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan annotation = configClass.getAnnotation(ComponentScan.class);
            String path = annotation.value();
            path = path.replace(".", "/");

            ClassLoader classLoader = ApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            assert resource != null;
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                List<File> files = FileUtil.getAllClassFile(file);
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    // 加载class文件
                    String className = fileName.substring(fileName.indexOf(path.replace("/", "\\")), fileName.indexOf(".class"))
                            .replace("\\", ".");
                    try {
                        Class<?> aClass = classLoader.loadClass(className);

                        // 接口就跳过
                        if (aClass.isInterface()) continue;

                        // 带了Component注解, 就作为一个Bean管理
                        if (aClass.isAnnotationPresent(Component.class)) {

                            // 如果类实现了BeanPostProcessor, 那么就加入到集合当中, 后面会调用
                            if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                BeanPostProcessor object = (BeanPostProcessor) aClass.newInstance();
                                beanPostProcessors.add(object);
                            }

                            Component component = aClass.getAnnotation(Component.class);
                            // 设置Bean的名字, 如果有设置就按设置的来
                            String beanName = component.value();
                            if ("".equals(beanName)) {
                                // 如果没设置, 看有没有接口, 如果有接口, 取接口的名字, 没有就取本身的名字
                                if (aClass.getInterfaces().length == 0) {
                                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                                } else {
                                    beanName = Introspector.decapitalize(aClass.getInterfaces()[0].getSimpleName());
                                }
                            }

                            // 根据类信息加载类数据
                            BeanDefinition beanDefinition = getBeanDefinition(aClass);
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        // 生成那些单例的Bean
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            if ("singleton".equals(entry.getValue().getScope())) {
                Object bean = createBean(entry.getKey(), entry.getValue());
                assert bean != null;
                singletonObjects.put(entry.getKey(), bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class<?> clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();

            // 依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowire.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            // Aware, 用于回调
            if (instance instanceof BeanNameAware) {
                BeanNameAware aware = (BeanNameAware) instance;
                aware.setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }

            // 初始化
            if (instance instanceof InitializeBean) {
                InitializeBean initializeBean = (InitializeBean) instance;
                initializeBean.afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }

            // 这里我们使用JDK的动态代理, 因此最后返回的是接口, 而不是类
            return instance;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private BeanDefinition getBeanDefinition(Class<?> aClass) {
        BeanDefinition beanDefinition = new BeanDefinition();
        // 设置Bean的类型
        beanDefinition.setType(aClass);
        // 设置单例还是多例的
        if (aClass.isAnnotationPresent(Scope.class)) {
            String scope = aClass.getAnnotation(Scope.class).value();
            beanDefinition.setScope(scope);
        } else {
            beanDefinition.setScope("singleton");
        }
        return beanDefinition;
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new RuntimeException();
        } else {
            String scope = beanDefinition.getScope();
            if ("singleton".equals(scope)) {
                Object bean = singletonObjects.get(beanName);
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
                return bean;
            } else {
                return createBean(beanName, beanDefinition);
            }
        }
    }
}
